//
//  LRPhotoBrowserController.swift
//  LRWeibo
//
//  Created by 雷路荣 on 15/12/30.
//  Copyright © 2015年 leilurong. All rights reserved.
//

import UIKit

import SVProgressHUD

let LRCellMargin: CGFloat = 10

class LRPhotoBrowserController: UIViewController {

    // MARK: - 属性
    /// 选中的indexPath
    private var selectedIndexPath: NSIndexPath
    
    /// 大图的url数组
    private var models: [LRPhotoBrowserModal]
    
    /// collectionView的布局
    private let layout = UICollectionViewFlowLayout()
    
    /// 重用标示
    private let reuseIdentifier = "PhotoBrowserCell"
    
    //MARK: - 构造方法
    init(indexPath: NSIndexPath, models: [LRPhotoBrowserModal]){
        self.selectedIndexPath = indexPath
        self.models = models
        super.init(nibName: nil, bundle: nil)
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    // 点击哪一张,进入图片浏览器就显示哪一张
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        // 如果collectioView使用autoLayout约束的是滚不动的,改成frame来设置宽高
        // 让collectionView滚动到指定的张数,不要使用动画
        collectionView.scrollToItemAtIndexPath(selectedIndexPath, atScrollPosition: UICollectionViewScrollPosition.Left, animated: false)
        // 设置页码
        setPageNum(selectedIndexPath.item + 1)
    }
    
    //设置页数
    private func setPageNum(currentPage: Int){
        pageLabel.text = "\(currentPage) / \(models.count)"
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        prepareUI()
    }
    // 准备UI
    func prepareUI(){
        //添加控件
        view.addSubview(bkgView)
        view.addSubview(collectionView)
        view.addSubview(pageLabel)
        view.addSubview(closeButton)
        view.addSubview(saveButton)
        //取消Autoresizing
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        pageLabel.translatesAutoresizingMaskIntoConstraints = false
        closeButton.translatesAutoresizingMaskIntoConstraints = false
        saveButton.translatesAutoresizingMaskIntoConstraints = false
        //设置约束
        bkgView.frame = view.bounds
        // 如果collectioView使用autoLayout约束的是滚不动的,改成frame来设置宽高
        collectionView.frame = CGRectMake(0, 0, view.bounds.width + LRCellMargin, view.bounds.height)
        // 页码
        // 水平centerX和父控件的centerX重合
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
        // 垂直距离父控件顶部20
        view.addConstraint(NSLayoutConstraint(item: pageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: view, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 20))
        
        // 关闭按钮的垂直方向,距离父控件底部8
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[cb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb":closeButton]))
        // 保存按钮的垂直方向,距离父控件底部8
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:[sb(35)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["sb":saveButton]))
        // 水平方向
        // 1.关闭按钮距离父控件左边8
        // 2.关闭按钮宽度75
        // 3.关闭按钮和保存按钮的间距>0
        // 4.保存按钮距离父控件右边8
        // 5.保存按钮宽度75
        view.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-8-[cb(80)]-(>=0)-[sb(80)]-8-|", options: NSLayoutFormatOptions(rawValue: 0), metrics: nil, views: ["cb":closeButton, "sb": saveButton]))
        
        // 设置collectionView
        setupCollectionView()
    }
    /// 设置collectionView
    private func setupCollectionView() {
        //注册cell
        collectionView.registerClass(LRPhotoBrowserCell.self, forCellWithReuseIdentifier: reuseIdentifier)
        //设置代理
        collectionView.dataSource = self
        collectionView.delegate = self
        // 设置cell大小,大小和屏幕一样大
        layout.itemSize = UIScreen.mainScreen().bounds.size
        // 水平滚动
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        // 分页
        collectionView.pagingEnabled = true
        // 间距
        layout.minimumInteritemSpacing = LRCellMargin
        layout.minimumLineSpacing = LRCellMargin
        // 取消弹簧效果
        collectionView.bounces = false
        // 取消滚动条
        collectionView.showsHorizontalScrollIndicator = false
        // 将最后一个cell往左边顶一个间距,否则会最后一张右边会看到间距
        collectionView.contentInset = UIEdgeInsetsMake(0, 0, 0, LRCellMargin)
        
        collectionView.backgroundColor = UIColor.clearColor()
    }
    // MARK: - 按钮点击事件
    /// 关闭控制器
    func close() {
        dismissViewControllerAnimated(true, completion: nil)
    }
    /// 保存图片
    func save() {
        //print("selectedIndexPath: \(selectedIndexPath), urls: \(URLs)")
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as! LRPhotoBrowserCell
        //获取正在显示的image
        if let image = cell.imageView.image {
            //- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo
            UIImageWriteToSavedPhotosAlbum(image, self, "image:didFinishSavingWithError:contextInfo:", nil)
        }else{
            SVProgressHUD.showErrorWithStatus("没有图片")
        }
    }
    //保存图片会调用的系统方法
    func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo: AnyObject) {
        if error != nil {
            SVProgressHUD.showErrorWithStatus("保存图片失败")
        }else{
            SVProgressHUD.showSuccessWithStatus("保存图片成功")
        }
    }
    //MARK: - 懒加载
    lazy var collectionView: UICollectionView = UICollectionView(frame: CGRectZero, collectionViewLayout: self.layout)
    /// 显示页数的label
    private lazy var pageLabel: UILabel = UILabel(fontSize: 13, textColor: UIColor.whiteColor())
    
    /// 关闭按钮
    private lazy var closeButton: UIButton = {
        let button = UIButton()
        // 设置文字
        button.setTitle("关闭", forState: UIControlState.Normal)
        // 设置按钮背景
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.addTarget(self, action: "close", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    /// 保存按钮
    private lazy var saveButton: UIButton = {
        let button = UIButton()
        // 设置文字
        button.setTitle("保存", forState: UIControlState.Normal)
        // 设置按钮背景
        button.setBackgroundImage(UIImage(named: "health_button_orange_line"), forState: UIControlState.Normal)
        button.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
        return button
    }()
    
    /// 背景视图
    private lazy var bkgView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.blackColor()
        return view
    }()
}

//MARK: - UICollectionView 数据源和代理方法------------------

extension LRPhotoBrowserController: UICollectionViewDataSource, UICollectionViewDelegate {
    
    func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return models.count
    }
    func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! LRPhotoBrowserCell
        // 设置cell的背景
        //cell.backgroundColor = UIColor.randomColor()
        // 给cell设置要显示图片的url
        let model = models[indexPath.item]
        cell.imageURL = model.largeURL
        //设置代理
        cell.delegate = self
        return cell
    }
    // 监听collectionView停止滚动
    func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
        // 获取当前显示的页数，不能通过该方法取，原因是可能会拿两个cell
        //selectedIndexPath = collectionView.indexPathsForVisibleItems().first!
        // 通过滚动值计算
        let index = Int(scrollView.contentOffset.x / scrollView.bounds.width)
        //记录显示cell的indexPath
        selectedIndexPath = NSIndexPath(forItem: index, inSection: 0)
        // 重新设置显示的页数
        setPageNum(index + 1)
    }
}

// 实现cell缩放的协议
extension LRPhotoBrowserController: LRPhotoBrowserCellDelegate {
    // 返回view让cell去修改alpha
    func viewForTransparent() -> UIView {
        return bkgView
    }
    
    // 关闭控制器
    func cellForDismissController() {
        // true会使用转场动画
        // false没有转场动画
        dismissViewControllerAnimated(false, completion: nil)
    }
    
    // 关闭时返回缩略图的位置
    func targetRectForDismissController() -> CGRect {
        return dismissTargetRect()
    }
}


// MARK: - 扩展 LRPhotoBrowserViewController 实现 UIViewControllerTransitioningDelegate
extension LRPhotoBrowserController: UIViewControllerTransitioningDelegate {
    
    /// 返回控制 modal 动画的对象
    func animationControllerForPresentedController(presented: UIViewController, presentingController presenting: UIViewController, sourceController source: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return LRPhotoBrowserModalAnimation()
    }
    
    /// 返回控制 dismiss 动画的对象
    func animationControllerForDismissedController(dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? {
        return LRPhotoBrowserDismissAnimation()
    }
}

// 扩展 CZPhotoBrowserController 转场动画相关的元素
extension LRPhotoBrowserController {
    /// 生成modal时的过渡视图
    func modalTempImageView() -> UIImageView {
        // 创建过度视图
        let tempImageView = UIImageView()
        // 获取到对应的模型
        let model = models[selectedIndexPath.item]
        // 获取缩略图iamgeView
        let imageView = model.imageView!
        // 设置过度视图的image
        tempImageView.image = imageView.image
        // 设置缩放模式
        tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
        tempImageView.clipsToBounds = true
        // 坐标系转换
        // 从imageView.superview的坐标系转换到 toCoordinateSpace 坐标系
        // Rect: 要转换的frame
        let newFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        //print("imageView.frame： \(newFrame)")
        // 设置过度视图frame
        tempImageView.frame = newFrame
        
        return tempImageView
    }
    
    // 计算modal的最终位置
    func modalTargetRect() -> CGRect {
        // 这个时候大图不一定有,我可以拿小图来计算,新浪小图和大图的长宽比是一样地
        let model = models[selectedIndexPath.item]
        // 获取缩略图,不能强制拆包,如果没有图片,就不计算大小
        if let image = model.imageView?.image {
            let newWidth = UIScreen.mainScreen().bounds.width
            // 新的高度 / 新的宽度 = 老的高度 / 老的宽度
            let newHeight = newWidth * image.size.height / image.size.width
            var offestY: CGFloat = 0
            // 判断是长图还是短图
            if newHeight < UIScreen.mainScreen().bounds.height {
                // 短图
                offestY = (UIScreen.mainScreen().bounds.height - newHeight) * 0.5
            } else {
                //
            }
            return CGRect(x: 0, y: offestY, width: newWidth, height: newHeight)
        }
        return CGRectZero
    }
    
    /// dismiss时的过渡视图
    func dismissTempImageView() -> UIImageView {
        // 创建过度视图
        let tempImageView = UIImageView()
        // 获取到正在显示的cell
        let cell = collectionView.cellForItemAtIndexPath(selectedIndexPath) as!
        LRPhotoBrowserCell
        // 获取到正在显示的image
        if let image = cell.imageView.image {
            //设置过度视图的image
            tempImageView.image = image
            //设置过度视图frame
            let newFrame = cell.imageView.superview!.convertRect(cell.imageView.frame, toCoordinateSpace: view)
            tempImageView.frame = newFrame
            //设置填充模式
            tempImageView.contentMode = UIViewContentMode.ScaleAspectFill
            //超出部分剪切掉
            tempImageView.clipsToBounds = true
        }
        return tempImageView
    }
    
    /// 返回dismiss时的目标frame
    func dismissTargetRect() -> CGRect {
        let model = models[selectedIndexPath.item]
        //获取缩略图
        let imageView = model.imageView!
        // 转换坐标系,从imageView的父控件转换到屏幕的左上角
        let NewFrame = imageView.superview!.convertRect(imageView.frame, toCoordinateSpace: view)
        return NewFrame
    }
}



























